<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Cms_Login extends Controller {

	private $template;
	
	public function before()
	{
		$this->template = View::factory('cms/login_template');
	}
	
	public function action_login()
	{ 
		// jeżeli już zalogowany
		if(Auth::instance()->logged_in()!= 0 || Auth::instance()->auto_login())
			Request::instance()->redirect('admin');
		if ($_POST)
		{
			$user = ORM::factory('user');
			$status = $user->login($_POST);
			if ($status)
			{		
				if(Auth::instance()->logged_in('login') != 0){
					Request::instance()->redirect('admin');
				}else{
					Request::instance()->redirect('login');
				}
			}else
			{
				Session::instance()->set('flash','<div class="flash-error">'.I18n::get('invalid_user_pass').'</div>');
			}
		}
		$view = View::factory('cms/login_form');
		$this->template->content = $view;
		echo $this->template;
	}
	public function action_logout()
	{
		Auth::instance()->logout();
		Request::instance()->redirect('/');		
	}
	
	public function action_remind()
	{
		$view = View::factory('cms/login_remind');
		$pass = 0;
		if($_POST)
		{
			$remail = trim($_POST['remail']);
			$user = DB::select('id')->from('users')
					  ->where('email','=', $remail)
					  ->execute()->current();
			if(!empty($user)){
				$salt = "abchefghjkmnpqrstuvwxyz0123456789";
				srand((double)microtime()*1000000);
				$i = 0;
				while ($i <= 7) {
					$num = rand() % 33;
					$tmp = substr($salt, $num, 1);
					$pass = $pass . $tmp;
					$i++;
				}
				$random_password = $pass;
				$db_password = Auth::instance()->hash_password($random_password);

				DB::update('users')->set(array('password'=>$db_password))
					->where('id','=',$user['id'])->execute();
					
				// wysyłanie wiadomości - Swift Mailer
				
				$content = i18n::get('new_password')." <b>".$random_password."</b>".i18n::get('remind_pass_cont');
				$footer = i18n::get('email_footer');
				Helpers::mailer($remail,i18n::get('remind_pass_2'),$content.$footer);
				Session::instance()->set('flash','<div style=\"color:green;\">Na podany e-mail zostało wysłane nowe hasło.</div>');
				Request::instance()->redirect('administracja');
			}else{
				Session::instance()->set('flash','<div class="flash-error">Podany e-mail nie został odnaleziony w bazie.</div>');
				Request::instance()->redirect('admin/remind');
			}
		}else{
			$this->template->content = $view;
		}
		echo $this->template;
	}
	
	public function action_ie($id)
	{
		$view = View::factory('backend/ie_error');
		$view->id = $id;
		echo $view;
	}
}